<template>
  <div class="login">
    <form @submit.prevent="handleLogin">
        <h2>登录</h2>
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        <div class="input-group">
          <input type="text" v-model="loginForm.username" placeholder="用户名" required @keypress="handleKeyPress">
        </div>
        <div class="input-group password-input-container">
          <input 
            :type="showPassword ? 'text' : 'password'" 
            v-model="loginForm.password" 
            placeholder="密码" 
            required 
            @keypress="handleKeyPress"
            class="password-input"
          >
          <button 
            type="button" 
            class="password-toggle" 
            @click="togglePasswordVisibility"
            :title="showPassword ? '隐藏密码' : '显示密码'"
          >
            <svg v-if="showPassword" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z" fill="currentColor"/>
            </svg>
            <svg v-else width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z" fill="currentColor"/>
            </svg>
          </button>
        </div>
        <div class="forgot-password-container">
          <a href="#" @click.prevent="goToForgotPassword" class="forgot-password">忘记密码？</a>
        </div>
        <button type="submit" class="login-btn" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>
      </form>
    
    <div class="divider">
      <span>或</span>
    </div>
    
    <div class="social-login">
      <router-link to="/wechat-login" class="wechat-login-btn">
        <span class="wechat-icon">📱</span>
        微信扫码登录
      </router-link>
    </div>
    
    <div class="register-link">
      还没有账号？<router-link to="/register">立即注册</router-link>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useUserStore } from '../stores/user';
import { useRouter } from 'vue-router';

// 状态管理和路由
const userStore = useUserStore();
const router = useRouter();

// 响应式数据
const loginForm = reactive({
  username: '',
  password: ''
});

const isLoading = ref(false);
const errorMessage = ref('');
const showPassword = ref(false);

// 表单验证规则
const validateForm = () => {
  if (!loginForm.username.trim()) {
    errorMessage.value = '请输入用户名';
    return false;
  }
  
  if (!loginForm.password) {
    errorMessage.value = '请输入密码';
    return false;
  }
  
  if (loginForm.password.length < 6) {
    errorMessage.value = '密码长度不能少于6位';
    return false;
  }
  
  return true;
};

/**
 * 处理用户登录
 */
const handleLogin = async () => {
  errorMessage.value = '';
  
  if (!validateForm()) {
    return;
  }

  isLoading.value = true;

  try {
    console.log('开始登录，用户名:', loginForm.username.trim());
    const success = await userStore.login({
      username: loginForm.username.trim(),
      password: loginForm.password
    });

    console.log('登录结果:', success);
    console.log('用户store状态:', {
      user: userStore.user,
      isAuthenticated: userStore.isAuthenticated
    });
    console.log('localStorage中的用户信息:', localStorage.getItem('user'));
    console.log('localStorage中的token:', localStorage.getItem('token'));

    if (success) {
      // 登录成功，跳转到首页或之前的页面
      const redirectPath = router.currentRoute.value.query.redirect || '/';
      console.log('登录成功，准备跳转到:', redirectPath);
      router.push(redirectPath);
    } else {
      // 登录失败但没有抛出异常的情况
      errorMessage.value = '用户名或密码错误，请重试';
    }
  } catch (error) {
    console.error('登录失败:', error);
    // 根据错误类型显示不同的错误信息
    if (error.response) {
      switch (error.response.status) {
        case 401:
          errorMessage.value = '用户名或密码错误';
          break;
        case 403:
          errorMessage.value = '账户已被禁用，请联系管理员';
          break;
        case 429:
          errorMessage.value = '登录尝试次数过多，请稍后再试';
          break;
        default:
          errorMessage.value = error.response.data?.message || '登录失败，请重试';
      }
    } else if (error.code === 'NETWORK_ERROR') {
      errorMessage.value = '网络连接失败，请检查网络设置';
    } else {
      errorMessage.value = '登录失败，请重试';
    }
  } finally {
    isLoading.value = false;
  }
};

/**
 * 切换密码显示/隐藏状态
 */
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

/**
 * 跳转到忘记密码页面
 */
const goToForgotPassword = () => {
  router.push('/forgot-password');
};



/**
 * 处理回车键登录
 * @param {KeyboardEvent} event - 键盘事件
 */
const handleKeyPress = (event) => {
  if (event.key === 'Enter') {
    handleLogin();
  }
};
</script>

<style scoped>
.login {
  max-width: 400px;
  margin: 0 auto;
  padding: 40px 30px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}

.login h2 {
  text-align: center;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.error-message {
  background: rgba(255, 107, 107, 0.1);
  border: 1px solid rgba(255, 107, 107, 0.3);
  color: #ff6b6b;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 20px;
  text-align: center;
  font-size: 14px;
}

form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-group {
  position: relative;
  width: 100%;
}

input {
  width: 100%;
  padding: 15px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
  font-size: 16px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

input:focus {
  outline: none;
  border-color: #00d4ff;
  box-shadow: 0 0 0 3px rgba(0, 212, 255, 0.1);
}

.password-input-container {
  position: relative;
}

.password-input {
  padding-right: 50px;
}

.password-toggle {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.password-toggle:hover {
  color: #00d4ff;
  background: rgba(0, 212, 255, 0.1);
}

.password-toggle:focus {
  outline: none;
  color: #00d4ff;
  background: rgba(0, 212, 255, 0.1);
}

.password-toggle svg {
  width: 20px;
  height: 20px;
}

.forgot-password-container {
  text-align: right;
  margin-bottom: 10px;
}

.forgot-password {
  color: rgba(255, 255, 255, 0.7);
  text-decoration: none;
  font-size: 14px;
  transition: color 0.3s ease;
}

.forgot-password:hover {
  color: #00d4ff;
}

.login-btn {
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  color: white;
  border: none;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
  width: 100%;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 212, 255, 0.3);
}

.divider {
  margin: 20px 0;
  text-align: center;
  position: relative;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: rgba(255, 255, 255, 0.2);
}

.divider span {
  background: rgba(26, 26, 46, 0.9);
  padding: 0 15px;
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
}

.social-login {
  margin-bottom: 20px;
}

.wechat-login-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  padding: 12px;
  background: linear-gradient(45deg, #07c160, #00d4ff);
  color: white;
  text-decoration: none;
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.wechat-login-btn:hover {
  background: linear-gradient(45deg, #06ad56, #00b8e6);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(7, 193, 96, 0.3);
}

.wechat-icon {
  font-size: 18px;
}

.register-link {
  text-align: center;
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
}

.register-link a {
  color: #00d4ff;
  text-decoration: none;
  font-weight: 600;
}

.register-link a:hover {
  color: #ff6b6b;
}

@media (max-width: 768px) {
  .login {
    margin: 20px;
    padding: 30px 20px;
  }
  
  .login h2 {
    font-size: 24px;
  }
}
</style>